// index.js
var app = getApp();
var util = require('../../utils/util.js')
var WxParse = require('../../wxParse/wxParse.js');
var login = require('../../utils/login.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    autoplay: true,
    interval: 3000,
    duration: 1000,
    goodsDetail: {},
    swiperCurrent: 0,
    hasMoreSelect: false,
    selectSize: "",
    selectSizePrice: 0,
    shopNum: 0,
    hideShopPopup: true,
    buyNumber: 0,
    buyNumMin: 0,
    buyNumMax: 0,
    propertyChildIds: "",
    propertyChildNames: "",
    canSubmit: false, //  选中规格尺寸时候是否允许加入购物车
    favorite: false,
    CurrentPid: 0,
    ReviewListLength: 0,
    animationData: "",
    showModalStatus: false,
    skuTitles: [],
    attrvalue: "",
    img: "",
    TotalCount: "",
    groupBuyInfor: {},
    timer: {
      days: 0,
      hours: 0,
      minutes: 0,
      seconds: 0,
      leftTime: 0
    },
    shouwTimer: true,
    showTimer: true,
    animationData2: "",
    showModalStatus2: false,
    productCode: "",
    pathGoods: "",
    mallName: "",
    isAccredit: false
  },

  preview: function () {
    var that = this
    wx.previewImage({
      current: that.data.productCode, // 当前显示图片的http链接
      urls: [that.data.productCode] // 需要预览的图片http链接列表
    })
  },

  //获取商品二维码
  getWxaCode: function () {
    var that = this
    wx.request({
      url: app.globalData.host + "/api/Store/GetWxaCodeFile",
      data: {
        storeId: app.globalData.storeId,
        path: '/pages/pintuan-details/index?p=' + this.data.CurrentPid,
        storeappid: app.globalData.storeAppId
      },
      success: function (res) {
        if (res.data.Code == 0) {
          if (res.data.Data) {
            that.setData({
              productCode: 'https://static.711688.net.cn/upload/user/' + res.data.Data
            })
          }
        }
      },
    })
  },
  // 弹出层
  showModal2: function (e) {
    var mallName = wx.getStorageSync("mallName")
    this.getWxaCode()
    // 显示遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    this.setData({
      animationData2: animation.export(),
      showModalStatus2: true,
      mallName: mallName
    })
    setTimeout(function () {
      this.setData({
        animationData: animation.export()
      })
    }.bind(this), 200)
  },
  hideModal2: function () {
    // 隐藏遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    this.setData({
      animationData2: animation.export(),
    })
    setTimeout(function () {
      this.setData({
        animationData2: animation.export(),
        showModalStatus2: false
      })
    }.bind(this), 200)
  },
  //事件处理函数
  swiperchange: function (e) {
    this.setData({
      swiperCurrent: e.detail.current
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (e) {
    var that = this;
    let currentPid = 0;
    let params = decodeURIComponent(e.scene);
    console.log('小程序码携带的参数', params);
    if (params && params != 'undefined') {//扫描小程序二维码进入
      let param = '';//参数
      let plist = '';
      if (params.indexOf('p-') != -1) {
        param = params.match(/p-(\S*)/)[1];//参数
        plist = param.toString().split('_');
      } else {
        param = params.match(/p=(\S*)/)[1];//参数
        plist = param.toString().split('#');
      }
      currentPid = plist[0];
    } else {
      currentPid = e.id;
    }
    that.setData({ CurrentPid: currentPid });
    that.getGroupBuyProductInfo();
  },
  intervalTimer: function () {
    var that = this;
    var timers = setInterval(function () {
      var groupBuyInfor = that.data.groupBuyInfor
      var EndTime = groupBuyInfor.EndTime
      var StartTime = groupBuyInfor.StartTime
      var timearr = EndTime.replace(" ", ":").replace(/\:/g, "-").split("-");//分割日期正则
      var year = timearr[0]
      var month = timearr[1]
      var day = timearr[2]
      var hour = timearr[3]
      var minute = timearr[4]
      var second = timearr[5]
      if (StartTime == EndTime || !that.data.shouwTimer || !that.data.showTimer) {
        clearInterval(timers)//清除计时
      } else {
        that.leftTimer(year, month, day, hour, minute, second)
      }
    }, 1000)
  },
  //时间计时
  leftTimer: function (year, month, day, hour, minute, second) {
    var that = this;
    var leftTime = (new Date(year, month - 1, day, hour, minute, second)) - (new Date()); //计算剩余的毫秒数 
    var days = parseInt(leftTime / 1000 / 60 / 60 / 24, 10); //计算剩余的天数 
    var hours = parseInt(leftTime / 1000 / 60 / 60 % 24, 10); //计算剩余的小时 
    var minutes = parseInt(leftTime / 1000 / 60 % 60, 10);//计算剩余的分钟 
    var seconds = parseInt(leftTime / 1000 % 60, 10);//计算剩余的秒数 
    days = that.checkTime(days);
    hours = that.checkTime(hours);
    minutes = that.checkTime(minutes);
    seconds = that.checkTime(seconds);
    var timer = {}
    timer.days = days
    timer.hours = hours
    timer.minutes = minutes
    timer.seconds = seconds
    timer.leftTime = leftTime
    if (leftTime > 0) {
      that.setData({
        timer: timer
      })
    } else {
      that.setData({
        showTimer: false
      })
    }
  },
  checkTime: function (i) { //将0-9的数字前面加上0，例1变为01 
    if (i < 10) {
      i = "0" + i;
    }
    return i;
  },
  //分享
  onShareAppMessage: function () {
    return {
      title: this.data.goodsDetail.ProductInfo.Name,
      path: '/pages/pintuan-details/index?id=' + this.data.CurrentPid,
      success: function (res) {
        // 转发
        wx.showModal({
          title: '提示',
          content: '转发成功',
          showCancel: false
        })
      },
      fail: function (res) {
        // 转发失败
      }
    }
  },
  selectGoods: function (e) {
    wx.navigateTo({
      url: '/pages/pingjia-list/index?pid=' + this.data.CurrentPid
    })
  },
  numJianTap: function () {
    if (this.data.buyNumber > this.data.buyNumMin) {
      var currentNum = this.data.buyNumber;
      currentNum--;
      this.setData({
        buyNumber: currentNum
      })
    }
  },
  numJiaTap: function (e) {
    if (e.detail.value) {
      if (this.data.buyNumber < this.data.buyNumMax) {
        this.setData({
          buyNumber: e.detail.value
        })
      }
    } else {
      if (this.data.buyNumber < this.data.buyNumMax) {
        var currentNum = this.data.buyNumber;
        currentNum++;
        this.setData({
          buyNumber: currentNum
        })
      }
    }
  },
  addShopCar: function (e) {
    if (e != 0) {
      var add = e.currentTarget.dataset.add
    }
    var that = this;
    if (this.data.buyNumber < 1) {
      wx.showModal({
        title: '提示',
        content: '暂时缺货哦~',
        showCancel: false
      })
      return;
    }

    wx.request({
      url: app.globalData.host + '/api/cart/AddProduct',
      data: {
        uid: app.globalData.userInfo.Uid,
        pid: that.data.CurrentPid,
        buyCount: that.data.buyNumber
      },
      success: function (res) {
        if (res.data.Code == 0) {
          that.setData({
            shopNum: res.data.Data
          });
          wx.showToast({
            title: '加入购物车成功',
            icon: 'success',
            duration: 2000,
            success: function () {
              if (add != 1) {
                that.goShopCar();
              }
            }
          })
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
        }
      }
    })
  },
  goShopCar: function () {
    let that = this;
    let back = '/pages/pintuan-details/index';
    let isAccredit = that.data.isAccredit;
    if (!isAccredit) {
      wx.showModal({
        title: '提示',
        content: '登陆小程序之后才能查看购物车，是否确认登陆',
        success: function (res) {
          if (res.confirm) {
            wx.redirectTo({
              url: '../accredit/index?back=' + back + '&id=' + that.data.CurrentPid,
            })
          }
        }
      })
      return;
    } else {
      wx.navigateTo({
        url: "/pages/shop-cart/index"
      });
    }
  },
  tobuy: function () {
    let that = this;
    let back = '/pages/pintuan-details/index';
    let isAccredit = that.data.isAccredit;
    if (!isAccredit) {
      wx.showModal({
        title: '提示',
        content: '登陆小程序之后方可购买商品,是否确认登陆',
        success: function (res) {
          if (res.confirm) {
            wx.redirectTo({
              url: '../accredit/index?back=' + back + '&id=' + that.data.CurrentPid,
            })
          }
        }
      })
      return;
    }
    if (that.data.buyNumber < 1) {
      wx.showModal({
        title: '提示',
        content: '暂时缺货哦~',
        showCancel: false
      })
      return;
    }
    that.addShopCar(0);
  },
  favorite: function (e) {
    var that = this;
    var pid = e.currentTarget.dataset.id;
    wx.request({
      url: app.globalData.host + '/api/user/ProductFavorite',
      data: {
        pid: pid,
        uid: app.globalData.userInfo.Uid
      },
      success: function (res) {
        if (res.data.Code == 0) {
          var oldF = that.data.favorite;
          if (oldF) {
            wx.showModal({
              title: '取消收藏成功',
              content: '',
              showCancel: false
            })
          } else {
            wx.showModal({
              title: '收藏成功',
              content: '',
              showCancel: false
            })
          }
          that.setData({ favorite: !oldF })
        }

      }
    })
  },
  initPage: function () {
    var that = this;
    var getLocationPromisified = util.wxPromisify(that.getShopCart)
    getLocationPromisified({

    }).then(that.checkFavorite())
      .then(that.getProductInfo())
      .then(that.pingjiaList())
      .catch(function (res) {
        console.error("failed" + res)
      })
  },

  //判断收藏
  checkFavorite: function () {
    var that = this;
    wx.request({
      url: app.globalData.host + '/api/user/CheckProductFavorite',
      data: {
        pid: that.data.CurrentPid,
        uid: app.globalData.userInfo.Uid
      },
      success: function (res) {
        var f = res.data.Data;
        that.setData({ favorite: f })
      }
    })
  },

  //获取购物车数据
  getShopCart: function () {
    var that = this;
    wx.request({
      url: app.globalData.host + '/api/cart/index',
      data: {
        uid: app.globalData.userInfo.Uid
      },
      success: function (res) {
        if (res.data.Code == 0) {
          that.setData({ shopNum: res.data.Data.TotalCount })
        }

      }
    })
  },

  //获取商品信息
  getProductInfo: function () {
    wx.showLoading({
      title: '加载中',
    })
    var that = this;
    wx.request({
      url: app.globalData.host + '/api/store/Product',
      data: {
        pid: that.data.CurrentPid
      },
      success: function (res) {
        wx.hideLoading();
        var p = res.data.Data;
        if (!p.ProductInfo || p.ProductInfo.State != 0) {
          wx.showModal({
            title: '商品已下架',
            content: '',
            showCancel: false
          })
          return;
        }
        p.ProductInfo.countPrice = parseInt(p.ProductInfo.MarketPrice - p.ProductInfo.ShopPrice)//市场价和本店价价格差
        if (p.ProductInfo.ShowImg) {
          p.ProductInfo.ShowImg = app.globalData.image800_800host + p.ProductInfo.ShowImg;
        }
        for (var i = 0; i < p.ProductImageList.length; i++) {
          p.ProductImageList[i].ShowImg = app.globalData.image800_800host + p.ProductImageList[i].ShowImg;
        }
        if (p.ExtGiftList) {
          for (var i = 0; i < p.ExtGiftList.length; i++) {
            p.ExtGiftList[i].ShowImg = app.globalData.image190_190host + p.ExtGiftList[i].ShowImg;
          }
        }

        var selectSizeTemp = "";
        var pnames = "";
        if (p.CurrProductSkuList.length > 0) {
          for (var i = 0; i < p.CurrProductSkuList.length; i++) {
            pnames += p.CurrProductSkuList[i].AttrName + ":";
            var value = p.CurrProductSkuList[i].AttrValue;
            if (p.CurrProductSkuList[i].IsInput) {
              value = p.CurrProductSkuList[i].InputValue;
            }
            selectSizeTemp = selectSizeTemp + " " + value;
            pnames += value + " "
          }
          that.setData({
            hasMoreSelect: true,
            selectSize: that.data.selectSize + selectSizeTemp,
            selectSizePrice: p.ProductInfo.ShopPrice,
            propertyChildNames: pnames
          });
        }
        if (p.ProductInfo.VideoSrc != "") {
          that.setData({
            showVideo: false
          })
        }
        that.setData({
          goodsDetail: p,
          selectSizePrice: p.ProductInfo.ShopPrice,
          buyNumMax: p.StockNumber,
          buyNumber: (p.StockNumber > 0) ? 1 : 0
        });
        WxParse.wxParse('article', 'html', p.ProductInfo.Description, that, 5);
      }
    })
  },

  //获取拼团信息
  getGroupBuyProductInfo: function () {
    var that = this
    wx: wx.request({
      url: app.globalData.host + '/api/Store/GetGroupBuyProductInfo?storeId=' + app.globalData.storeId + '&pid=' + that.data.CurrentPid,
      success: function (res) {
        if (res.data.Code == 0) {
          var GroupBuyInfor = {}
          GroupBuyInfor.GroupBuyPrice = res.data.Data.GroupBuyPrice//团购价
          GroupBuyInfor.StartTime = res.data.Data.GroupBuy.StartTime//开始时间
          GroupBuyInfor.EndTime = res.data.Data.GroupBuy.EndTime//结束时间
          GroupBuyInfor.Status = res.data.Data.GroupBuy.Status// 0:开启，1：关闭
          GroupBuyInfor.LimitBuyerCount = res.data.Data.GroupBuy.LimitBuyerCount//拼团人数
          GroupBuyInfor.BuyStatus = res.data.Data.BuyStatus//还差人数
          that.setData({
            groupBuyInfor: GroupBuyInfor
          })
        }
      }
    })
  },
  //获取评价列表
  pingjiaList: function () {
    var that = this;
    var postDatalist = {
      uid: app.globalData.userInfo.Uid,
      page: 1
    };
    wx.request({
      url: app.globalData.host + '/api/store/productreviewlist?pid=' + that.data.CurrentPid + '&page=1',
      success: (res) => {
        if (res.data.Code == 0) {
          var ReviewListTwo = [];
          that.setData({
            ReviewListLength: res.data.Data.ProductReviewList.length,
            TotalCount: res.data.Data.PageModel.TotalCount
          })
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    if (app.globalData.userInfo) {
      console.log("用户信息存在")
      that.initPage();
      that.getWxaCode();
      util.isAccredit(function (isAccredit) {
        that.data.isAccredit = isAccredit;
      });
      if (that.data.shouwTimer) {
        that.intervalTimer();
      }
    } else {
      console.log("用户信息不存在,延时加载")
      setTimeout(function () {
        this.onShow();
      }.bind(that), 1000)
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    this.setData({
      shouwTimer: false
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    // 页面相关事件处理函数--监听用户下拉动作
    wx.stopPullDownRefresh();
  },

  /**
 * 生成产品海报
 */

  //下载产品图片
  getAvaterInfo: function () {
    wx.showLoading({ title: '生成中...', mask: true, });
    var that = this;
    that.setData({ showpost: true })
    var goodsDetail = that.data.goodsDetail;
    var productImage = goodsDetail.ProductImageList[0].ShowImg;
    if (productImage) {
      wx.downloadFile({
        url: productImage,
        success: function (res) {
          wx.hideLoading();
          if (res.statusCode === 200) {
            var productSrc = res.tempFilePath;
            that.getQrCode(productSrc);
          } else {
            wx.showToast({
              title: '产品图片下载失败！',
              icon: 'none',
              duration: 2000,
              success: function () {
                var productSrc = "";
                that.getQrCode(productSrc);
              }
            })
          }
        }
      })
    } else {
      wx.hideLoading();
      var productSrc = "";
      that.getQrCode(productSrc);
    }
  },

  //下载二维码
  getQrCode: function (productSrc) {
    wx.showLoading({ title: '生成中...', mask: true, });
    var that = this;
    var productCode = that.data.productCode;
    if (productCode) {
      wx.downloadFile({
        url: productCode,
        success: function (res) {
          wx.hideLoading();
          if (res.statusCode === 200) {
            var codeSrc = res.tempFilePath;
            that.sharePosteCanvas(productSrc, codeSrc);
          } else {
            wx.showToast({
              title: '二维码下载失败！',
              icon: 'none',
              duration: 2000,
              success: function () {
                var codeSrc = "";
                that.sharePosteCanvas(productSrc, codeSrc);
              }
            })
          }
        }
      })
    } else {
      wx.hideLoading();
      var codeSrc = "";
      that.sharePosteCanvas(productSrc, codeSrc);
    }
  },

  //canvas绘制分享海报
  sharePosteCanvas: function (avaterSrc, codeSrc) {
    wx.showLoading({
      title: '生成中...',
      mask: true,
    })
    var that = this;
    var productInfo = that.data.goodsDetail.ProductInfo;
    const ctx = wx.createCanvasContext('myCanvas');
    var width = "";
    wx.createSelectorQuery().select('#canvas-container').boundingClientRect(function (rect) {
      var height = rect.height;
      var right = rect.right;
      width = rect.width;
      var left = rect.left;
      ctx.setFillStyle('#fff');
      ctx.fillRect(0, 0, rect.width, height);

      //头像
      if (avaterSrc) {
        ctx.drawImage(avaterSrc, 0, 0, width, width);
        ctx.setFontSize(14);
        ctx.setFillStyle('#fff');
        ctx.setTextAlign('left');
      }


      //产品名称
      if (productInfo.Name) {
        const CONTENT_ROW_LENGTH = 24; // 正文 单行显示字符长度
        let [contentLeng, contentArray, contentRows] = that.textByteLength((productInfo.Name).substr(0, 40), CONTENT_ROW_LENGTH);
        ctx.setTextAlign('left');
        ctx.setFillStyle('#000');
        ctx.setFontSize(14);
        let contentHh = 22 * 1;
        for (let m = 0; m < contentArray.length; m++) {
          ctx.fillText(contentArray[m], 15, width + 35 + contentHh * m);
        }
      }


      //产品金额
      if (productInfo.ShopPrice || productInfo.ShopPrice == 0) {
        ctx.setFontSize(25);
        ctx.setFillStyle('#F57509');
        ctx.setTextAlign('left');
        ctx.fillText("¥" + productInfo.ShopPrice, left, width + 110); //电话
      }


      //  绘制二维码cardInfo.CardInfo.QrCode
      if (codeSrc) {
        ctx.drawImage(codeSrc, left + 185, width + 15, width / 4, width / 4)
        ctx.setFontSize(10);
        ctx.setFillStyle('#000');
        ctx.fillText("微信扫码或长按识别", left + 175, width + 110);
      }

    }).exec()

    setTimeout(function () {
      ctx.draw();
      wx.hideLoading();
    }, 1000)

  },

  textByteLength(text, num) { // text为传入的文本  num为单行显示的字节长度
    let strLength = 0; // text byte length
    let rows = 1;
    let str = 0;
    let arr = [];
    for (let j = 0; j < text.length; j++) {
      if (text.charCodeAt(j) > 255) {
        strLength += 2;
        if (strLength > rows * num) {
          strLength++;
          arr.push(text.slice(str, j));
          str = j;
          rows++;
        }
      } else {
        strLength++;
        if (strLength > rows * num) {
          arr.push(text.slice(str, j));
          str = j;
          rows++;
        }
      }
    }
    arr.push(text.slice(str, text.length));
    return [strLength, arr, rows] //  [处理文字的总字节长度，每行显示内容的数组，行数]
  },

  //点击保存到相册
  saveShareImg: function () {
    var that = this;
    wx.showLoading({
      title: '正在保存',
      mask: true,
    })
    setTimeout(function () {
      wx.canvasToTempFilePath({
        canvasId: 'myCanvas',
        success: function (res) {
          wx.hideLoading();
          var tempFilePath = res.tempFilePath;
          wx.saveImageToPhotosAlbum({
            filePath: tempFilePath,
            success(res) {
              wx.showModal({
                content: '图片已保存到相册，赶紧晒一下吧~',
                showCancel: false,
                confirmText: '好的',
                confirmColor: '#333',
                success: function (res) {
                  that.closePoste();
                  if (res.confirm) { }
                },
                fail: function (res) { }
              })
            },
            fail: function (res) {
              wx.showToast({
                title: res.errMsg,
                icon: 'none',
                duration: 2000
              })
            }
          })
        }
      });
    }, 1000);
  },
  closePoste: function () {
    this.setData({ showpost: false })
  }
})